﻿using SSCMS.Parse;
using SSCMS.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WF.BeOnDuty.Models;

namespace WF.BeOnDuty.Stl
{
    public class StlDutyInfo : IPluginParseAsync
    {

        public string ElementName => "stl:wfDuty";
        private const string AttributeType = "type";

        public async Task<string> ParseAsync(IParseStlContext context)
        {
            var type = string.Empty;

            foreach (var name in context.StlAttributes.AllKeys)
            {
                var attributeName = name.ToLower();
                var value = context.StlAttributes[name];
                if (attributeName.Equals(AttributeType))
                {
                    type = value.ToLower();
                }
            }

            return !TryGetContextItem(context, out var rank, out var itemIndex)
                ? string.Empty
                :  ParseImplAsync(rank, itemIndex, type);
        }


        private static bool TryGetContextItem(IParseStlContext context, out Models.DutyInfo model, out int itemIndex)
        {
            model = context.Get<Models.DutyInfo>($"{nameof(DutyInfo)}:duty");
            itemIndex = context.Get<int>($"{nameof(DutyInfo)}:itemIndex");

            return model != null && itemIndex > 0;
        }

        private string ParseImplAsync(Models.DutyInfo model, int itemIndex, string type)
        {
            var parsedContent = string.Empty;

            if (type == "itemindex" || type == "index")
            {
                parsedContent = itemIndex.ToString();
            }
            else 
            {
                parsedContent = model.Get(type).ToString();
            }
            return parsedContent;
        }
    }
}
